import http from './http';

export interface SkuSearchParams {
  page?: number;
  pageSize?: number;
  invCode?: string;      // 物料编码
  invName?: string;      // 产品名
  productType?: string;  // 产品类型
  status?: string;       // 状态（后端原样传）
}

export interface SkuBomItemApi {
  bom: {
    bomType: string;
    classId: number;
    className: string;
    id: string;
    invCode: string;
    name: string;
    productType: string;
  };
  quantity: number;
}

export interface SkuRecordApi {
  id: string;
  invCode: string;
  name: string;
  productType: string;
  status: string;
  port: number;      // 港杂费
  cutting: number;   // 裁切费用
  labor: number;     // 人工
  bomS: SkuBomItemApi[];
}

export interface PageEnvelope<T> {
  code: number;
  data: {
    records: T[];
    total: number;
    size: number;
    current: number;
    pages: number;
  };
  msg: string;
}

export async function fetchSkuList(params: SkuSearchParams){
  const { page=1, pageSize=10, invCode='', invName='', productType='', status='' } = params || {};
  const body = { page, pageSize, invCode, invName, productType, status };
  const envelope = await http.post<PageEnvelope<SkuRecordApi>>('/api/sku/search', body);
  if((envelope as any).code !== 200) throw new Error((envelope as any).msg || '产品查询失败');
  return (envelope as any).data;
}

// 获取编码平台上产品详细信息（用于动态属性展示）
export async function fetchSkuEncodingDetail(materialCode: string){
  if(!materialCode) throw new Error('缺少物料编码');
  const envelope = await http.get<any>(`/api/encoding-platform/search/detail?materialCode=${encodeURIComponent(materialCode)}`);
  if((envelope as any).code !== 200) throw new Error((envelope as any).msg || '获取详情失败');
  return (envelope as any).data;
}

// 新增产品信息（包括 BOM 和非物料成本）
export async function addSku(body: any){
  const envelope = await http.post<any>('/api/sku/add', body);
  if((envelope as any).code !== 200) throw new Error((envelope as any).msg || '新增失败');
  return (envelope as any).data;
}

// 编辑产品信息（包括 BOM 和非物料成本）
export async function editSku(body: any){
  const envelope = await http.post<any>('/api/sku/edit', body);
  if((envelope as any).code !== 200) throw new Error((envelope as any).msg || '编辑失败');
  return (envelope as any).data;
}
